package com.kczd.jinlan.view.shouye.fragment;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.normaladapter.ShopdetailsAdapter;
import com.kczd.jinlan.db.shopcar.DbUtils;
import com.kczd.jinlan.model.Goods;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.view.shouye.Attribute;
import com.kczd.jinlan.view.shouye.DetailsFoodActivity;
import com.kczd.jinlan.view.shouye.FlowLayout;
import com.kczd.jinlan.view.shouye.TagAdapter;
import com.kczd.jinlan.view.shouye.TagFlowLayout;
import com.kczd.jinlan.view.shouye.classActivity.ClassifydetilActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.recker.flybanner.FlyBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 商品页面
 * zhangy
 * Created by Administrator on 2017/5/19.
 */

public class ShangPingFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "ShangPingFragment.class";

    private List<String> mBaozhuangDate;//外包装属性数据
    private List<String> mzhongliangDate;//重量属性数据
    private List<String> mFailureSkuDate;//无库存或不能选的所有组合sku
    private List<String> mAllSkuDate;//所有的组合sku


    private LayoutInflater mInflater;

    private Attribute BaozhuangAtt = new Attribute();
    private Attribute ZhongliangAtt = new Attribute();

    private int DefaultColor;//临时记录的颜色
    private int DefaultSize;//临时记录的大小

    private int Color;
    private int Size;

    private String ColorStr;
    private String SizeStr;


    private String Sku;


    private FlyBanner mBannerNet;//加载网络图片
    private String[] mImagesUrl;
    //private String[] mImagesUrl = { "http://www.weiantang.com/public/upload/goods/2017/06-06/1ac5363ccdc6a40c98bb19c945575092.jpg" };
    // String[] titles = {"为", "梦", "想", "坚", "持", "呀"};

    private View view;
    // private PicsView mPicsviewpager;
    private ShopdetailsAdapter shopdetailsAdapter;
    private ListView product_presentation;//产品介绍
    private ListView product_show;//产品展示
    private ListView choice_criterion;//选择标准
    private ListView package_show;//包装展示

    private TextView kefu;
    private TextView title;
    private TextView price;
    private ImageView img;

    private ImageView mAnimImageView;
    private Animation mAnimation;
    private TextView mNumTextView;
    private PopupWindow mPopupWindow;
    private TextView mTextView;
    private int goodsNum = 0;
    List<Goods> list = ShangchengFragment.telist;
    List<List<String>> itemListid = ClassifydetilActivity.itemListid;
    private LinearLayout shop_guige_ll;
    private TextView shop_guige;
    private TextView shop_kucun;
    private  JSONArray imgsjs;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.shangping_fragment, null);
        mInflater = LayoutInflater.from(getActivity());

        int position= DetailsFoodActivity.position;
        initView();
           setView(position);

        return view;
    }

    /**
     * 加载网页图片
     */
    private void initNetBanner() {
        mBannerNet = (FlyBanner) view.findViewById(R.id.banner_1);

        List<String> imgesUrl = new ArrayList<>();
        for (int i = 0; i < mImagesUrl.length; i++) {
            imgesUrl.add(mImagesUrl[i]);
        }
        mBannerNet.setImagesUrl(imgesUrl);

        mBannerNet.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                toast("点击了第" + position + "张图片");
            }
        });
    }

    private void toast(String str) {
        Toast.makeText(getContext(), str, Toast.LENGTH_SHORT).show();
    }

    private void initView() {
        product_presentation = (ListView) view.findViewById(R.id.id_product_presentation);
        product_show = (ListView) view.findViewById(R.id.id_product_show);
        choice_criterion = (ListView) view.findViewById(R.id.id_choice_criterion);
        package_show = (ListView) view.findViewById(R.id.id_package_show);
        mAnimImageView = (ImageView) view.findViewById(R.id.cart_anim_icon);  //购物车动画
        mNumTextView = (TextView) view.findViewById(R.id.detail_shopping_new);//加入购物车的数量
        mAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.cart_anim);
        shop_guige_ll = (LinearLayout) view.findViewById(R.id.shop_guige_ll);//规格名称
        mTextView = (TextView) view.findViewById(R.id.id_jiaru_car);//加入购物车
        // mPicsviewpager = (PicsView)view. findViewById(R.id.picsviewpager);//滚动页面
        shop_guige = (TextView) view.findViewById(R.id.shop_guige);//规格value
        shop_kucun = (TextView) view.findViewById(R.id.shop_kucun);//库存
        title = (TextView) view.findViewById(R.id.shop_name);
        price = (TextView) view.findViewById(R.id.shop_price);
        img = (ImageView) view.findViewById(R.id.shop_img);
        kefu = (TextView) view.findViewById(R.id.id_kefu);

        kefu.setOnClickListener(this);
        shop_guige_ll.setOnClickListener(this);
        mTextView.setOnClickListener(this);

        // shopdetailsAdapter=new ShopdetailsAdapter(imgs);
        product_presentation.setAdapter(shopdetailsAdapter);//产品介绍
        product_show.setAdapter(shopdetailsAdapter);//产品展示
        choice_criterion.setAdapter(shopdetailsAdapter);//选择标准
        package_show.setAdapter(shopdetailsAdapter);//包装展示

     /*   List<ImageView> imgList = new ArrayList<ImageView>();
        for(int i = 0; i < imgs.length; i++){
            ImageView iv = new ImageView(getActivity());
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setImageResource(imgs[i]);
            imgList.add(iv);
        }*/
        // 初始化数据
        //  mPicsviewpager.setTitlesAndImages(titles, imgList);

        // 设置点击事件
       /* mPicsviewpager.setOnLunBoClickListener(new PicsView.OnLunBoClickListener() {

            @Override
            public void clickLunbo(int position) {
                System.out.println("点击有效");
                Toast.makeText(getActivity(), "点击有效，位置为：" + position, Toast.LENGTH_SHORT).show();
            }
        });*/


        mAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // TODO Auto-generated method stub
                goodsNum++;
                mNumTextView.setText(goodsNum + "");
                mAnimImageView.setVisibility(View.INVISIBLE);
            }
        });
    }


    public void setView(final int position) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                getShopDetails(position);
            }
        }).start();
    }


    String url = Config.net_addr + "goods/goods_info";

    public void getShopDetails(int position) {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("id", list.get(position).getCid())
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    String original_img = null;
    String goods_sn = null;
    int goods_id = -1;
    String goods_name = null;
    String goods_remark = null;
    String goods_price = null;
    String store_count = null;
    String weight = null;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG, val);
            val = val.substring(val.indexOf("{"), val.lastIndexOf("}") + 1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if (Config.code.equals(jsonResult.getString("code"))) {

                    JSONObject js = jsonResult.getJSONObject("data");
                    goods_id = Integer.parseInt(js.getString("goods_id"));
                    goods_name = js.getString("goods_name");
                    goods_price = js.getString("goods_price");
                    goods_remark = js.getString("goods_remark");
                    store_count = js.getString("store_count");
                    goods_sn = js.getString("goods_sn");
                    weight = js.getString("weight");
                    original_img = js.getString("original_img");
                    imgsjs = js.getJSONArray("goods_images_list");
                    mImagesUrl = new String[imgsjs.length()];
                    for (int i = 0; i < imgsjs.length(); i++) {
                        String imgurl = imgsjs.getJSONObject(i).getString("image_url");

                        mImagesUrl[i] = imgurl;
                    }

                    JSONObject jbs = js.getJSONObject("filter_spec");
                    JSONArray jas = jbs.getJSONArray("外包装");
                    mBaozhuangDate = new ArrayList<>();
                    mzhongliangDate = new ArrayList<>();
                    for (int i = 0; i < jas.length(); i++) {
                        String item = jas.getJSONObject(i).getString("item");
                        String item_id=jas.getJSONObject(i).getString("item_id");
                        mBaozhuangDate.add(item);
                    }
                    JSONArray jaw = jbs.getJSONArray("重量");
                    for (int j = 0; j < jas.length(); j++) {
                        String item = jaw.getJSONObject(j).getString("item");
                        String item_id=jas.getJSONObject(j).getString("item_id");
                        mzhongliangDate.add(item);

                    }
                    title.setText(goods_name);
                    price.setText("¥ " + goods_price);
                    BaozhuangAtt.aliasName.addAll(mBaozhuangDate);
                    ZhongliangAtt.aliasName.addAll(mzhongliangDate);

                    //所有的Sku
                    mAllSkuDate = new ArrayList<>();
                    for (int i = 0; i < mzhongliangDate.size(); i++) {
                        String Colorstr = mzhongliangDate.get(i);
                        for (int j = 0; j < mBaozhuangDate.size(); j++) {
                            String s = mBaozhuangDate.get(j);
                            mAllSkuDate.add(Colorstr + ":" + s);
                        }
                    }

                    mFailureSkuDate = new ArrayList<>();
                    Select(null);

                    // 显示图片的配置
                    DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.img_loading)
                            .showImageOnFail(R.mipmap.img_fail).cacheInMemory(true).cacheOnDisk(true)
                            .bitmapConfig(Bitmap.Config.RGB_565).build();
                    ImageLoader.getInstance().displayImage(original_img, img, options);
                    initNetBanner();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

   /* @Override
    public void onPause() {
        // 停止图片轮播
        mPicsviewpager.stopAutoScroll();
        super.onPause();
    }

    @Override
    public void onResume() {
        // 开启图片轮播
        mPicsviewpager.startAutoScroll();
        super.onResume();
    }*/

    @Override
    public void onClick(View v) {
        CommodityAttribute mCommodityAttribute = new CommodityAttribute(getActivity());
        switch (v.getId()) {
            case R.id.id_kefu:
                //拨打客服电话
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                        + "15249088687".trim()));
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                startActivity(intent);
                break;
            case R.id.shop_guige_ll://选择规格
                mCommodityAttribute.showAtLocation(mTextView, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.id_jiaru_car://加入购物车
                mCommodityAttribute.showAtLocation(mTextView, Gravity.BOTTOM, 0, 0);

                break;

            default:
                break;
        }
    }


    //对数据进行解析
    public void Select(String TureSku) {
        if (TureSku == null) {
            Sku = mAllSkuDate.get(0);
        } else {
            Sku = TureSku;
        }

        String[] split = Sku.split(":");
        String splitsColor = split[0];
        String splitsSize = split[1];
        ZhongliangAtt.FailureAliasName.clear();
        for (int i = 0; i < mzhongliangDate.size(); i++) {
            if (splitsColor.equals(mzhongliangDate.get(i))) {
                DefaultColor = i;
                Color = DefaultColor;
            }
            //拿到颜色属性不可选的属性集合
            String sku = mzhongliangDate.get(i) + ":" + splitsSize;
            for (int j = 0; j < mFailureSkuDate.size(); j++) {
                if (sku.equals(mFailureSkuDate.get(j))) {
                    ZhongliangAtt.FailureAliasName.add(mzhongliangDate.get(i));
                }
            }
        }
        BaozhuangAtt.FailureAliasName.clear();
        for (int i = 0; i < mBaozhuangDate.size(); i++) {
            if (splitsSize.equals(mBaozhuangDate.get(i))) {
                DefaultSize = i;
                Size = DefaultSize;
            }
            //拿到大小属性不可选的属性集合
            String sku = splitsColor + ":" + mBaozhuangDate.get(i);
            for (int j = 0; j < mFailureSkuDate.size(); j++) {
                if (sku.equals(mFailureSkuDate.get(j))) {
                    BaozhuangAtt.FailureAliasName.add(mBaozhuangDate.get(i));
                }
            }
        }
    }

//    public void date() {

    //无库存的组合Sku
//        mFailureSkuDate = new ArrayList<>();
//        mFailureSkuDate.add("蓝花:40-41");
//        mFailureSkuDate.add("蓝花:42-43");
//        mFailureSkuDate.add("蓝花:44-45");
//        mFailureSkuDate.add("青花瓷:40-41");
//        mFailureSkuDate.add("青花瓷:42-43");
//        mFailureSkuDate.add("青花瓷:44-45");
//        mFailureSkuDate.add("玫红:40-41");
//        mFailureSkuDate.add("玫红:42-43");
//        mFailureSkuDate.add("玫红:44-45");
//        mFailureSkuDate.add("黄色:40-41");
//        mFailureSkuDate.add("黄色:42-43");
//        mFailureSkuDate.add("黄色:44-45");
//        mFailureSkuDate.add("迷彩:36-37");
//        mFailureSkuDate.add("迷彩:38-39");
//        mFailureSkuDate.add("黑色:36-37");
//        mFailureSkuDate.add("黑色:38-39");
//        mFailureSkuDate.add("蓝色:36-37");
//        mFailureSkuDate.add("蓝色:38-39");

//        //所有的Sku
//        mAllSkuDate = new ArrayList<>();
//        for (int i = 0; i < mzhongliangDate.size(); i++) {
//            String Colorstr = mzhongliangDate.get(i);
//            for (int j = 0; j < mBaozhuangDate.size(); j++) {
//                String s = mBaozhuangDate.get(j);
//                mAllSkuDate.add(Colorstr + ":" + s);
//            }
//        }
//    }

    /**
     * 商品属性PopupWind
     */

    public class CommodityAttribute extends PopupWindow {
        private View CommodityAttributeView;
        private TagFlowLayout mTfSize;
        private TagFlowLayout mTfColor;
        private TextView mTvOk;
        private final mTagAdapter mSizeAdapter;
        private final mTagAdapter mColorAdapter;
        private ImageView shop_window_img;
        private TextView xinghaoshop;
        private TextView iv_sub, iv_add;
        private TextView tv_show_num,tv_price;
        int currentCount = 1;

        public CommodityAttribute(Activity context) {
            super(context);
            Select(Sku);

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            CommodityAttributeView = inflater.inflate(R.layout.sku_popupwindow, null);
            mTfSize = (TagFlowLayout) CommodityAttributeView.findViewById(R.id.tf_size);
            mTfColor = (TagFlowLayout) CommodityAttributeView.findViewById(R.id.tf_color);
            mTvOk = (TextView) CommodityAttributeView.findViewById(R.id.popupwind_ok);
            shop_window_img = (ImageView) CommodityAttributeView.findViewById(R.id.shop_img);
            xinghaoshop = (TextView) CommodityAttributeView.findViewById(R.id.xinghao_shop);
            iv_add = (TextView) CommodityAttributeView.findViewById(R.id.tv_add);
            iv_sub = (TextView) CommodityAttributeView.findViewById(R.id.tv_reduce);
            tv_price= (TextView) CommodityAttributeView.findViewById(R.id.price_id);
            tv_show_num = (TextView) CommodityAttributeView.findViewById(R.id.tv_show_num);

            iv_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentCount++;
                    tv_show_num.setText(currentCount + "");
                }
            });
            iv_sub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currentCount--;
                    tv_show_num.setText(currentCount + "");
                }
            });

            xinghaoshop.setText(goods_sn);
            // 显示图片的配置
            DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap.img_loading)
                    .showImageOnFail(R.mipmap.img_fail).cacheInMemory(true).cacheOnDisk(true)
                    .bitmapConfig(Bitmap.Config.RGB_565).build();
            ImageLoader.getInstance().displayImage(original_img, shop_window_img, options);

            mColorAdapter = new mTagAdapter(ZhongliangAtt);
            mTfColor.setAdapter(mColorAdapter);
            mColorAdapter.setSelectedList(Color);
            ColorStr = mzhongliangDate.get(Color);

            mSizeAdapter = new mTagAdapter(BaozhuangAtt);
            mTfSize.setAdapter(mSizeAdapter);
            mSizeAdapter.setSelectedList(Size);
            SizeStr = mBaozhuangDate.get(Size);

            //颜色属性标签点击事件
            mTfColor.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                boolean is;

                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {

                    is = false;
                    //从Base类中拿到不可点击的属性名称进行比较
                    List<String> st = ZhongliangAtt.getFailureAliasName();
                    for (int i = 0; i < st.size(); i++) {
                        if (st.get(i).equals(mzhongliangDate.get(position))) {
                            is = true;
                        }
                    }
                    //如是不可点击就进接return 这样就形成了不可点击的假像，达到了我们的目的
                    if (is) {
                        return true;
                    }

                    if (position == DefaultColor) {
                        DefaultColor = -1;
                        ColorStr = "";
                        BaozhuangAtt.FailureAliasName.clear();
                        TagAdapNotify(mSizeAdapter, DefaultSize);
                        return true;
                    } else {
                        DefaultColor = position;
                        ColorStr = mzhongliangDate.get(position);
                    }
                    BaozhuangAtt.FailureAliasName.clear();
                    for (int i = 0; i < mBaozhuangDate.size(); i++) {
                        String sku = ColorStr + ":" + mBaozhuangDate.get(i);
                        for (int j = 0; j < mFailureSkuDate.size(); j++) {
                            if (sku.equals(mFailureSkuDate.get(j))) {
                                BaozhuangAtt.FailureAliasName.add(mBaozhuangDate.get(i));
                            }
                        }
                    }
                    TagAdapNotify(mSizeAdapter, DefaultSize);
                    return true;
                }
            });


            //大小属性标签点击事件
            mTfSize.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                boolean is;

                @Override
                public boolean onTagClick(View view, int position, FlowLayout parent) {

                    is = false;
                    List<String> st = BaozhuangAtt.getFailureAliasName();
                    for (int i = 0; i < st.size(); i++) {
                        if (st.get(i).equals(mBaozhuangDate.get(position))) {
                            is = true;
                        }
                    }
                    if (is) {
                        return true;
                    }

                    if (position == DefaultSize) {
                        DefaultSize = -1;
                        SizeStr = "";
                        ZhongliangAtt.FailureAliasName.clear();
                        TagAdapNotify(mColorAdapter, DefaultColor);
                        return true;
                    } else {
                        DefaultSize = position;
                        SizeStr = mBaozhuangDate.get(position);
                    }

                    ZhongliangAtt.FailureAliasName.clear();
                    for (int i = 0; i < mzhongliangDate.size(); i++) {
                        String sku = mzhongliangDate.get(i) + ":" + SizeStr;
                        for (int j = 0; j < mFailureSkuDate.size(); j++) {
                            if (sku.equals(mFailureSkuDate.get(j))) {
                                ZhongliangAtt.FailureAliasName.add(mzhongliangDate.get(i));
                            }
                        }
                    }
                    TagAdapNotify(mColorAdapter, DefaultColor);

                    return true;
                }
            });


            mTvOk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (DefaultColor == -1 || DefaultSize == -1) {
                        Toast.makeText(getActivity(), "请选择属性", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    mAnimImageView.setVisibility(View.VISIBLE);
                    mAnimImageView.startAnimation(mAnimation);


                    //保存在数据库中
                    DbUtils.addData(goods_name, original_img, weight, ColorStr , SizeStr, goods_price, goods_id, Integer.parseInt(tv_show_num.getText().toString()));
                    shop_guige.setText("规格:" + ColorStr + "," + SizeStr);
//                    Sku = ColorStr + ":" + SizeStr;
//                    Size = DefaultSize;
//                    Color = DefaultColor;
                    dismiss();
                }
            });


            // 设置SelectPicPopupWindow的View
            this.setContentView(CommodityAttributeView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewPager.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewPager.LayoutParams.WRAP_CONTENT);
            // 在PopupWindow里面就加上下面两句代码，让键盘弹出时，不会挡住pop窗口。
            this.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            this.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            // 设置popupWindow以外可以触摸
            this.setOutsideTouchable(true);
            // 以下两个设置点击空白处时，隐藏掉pop窗口
            this.setFocusable(true);
            this.setBackgroundDrawable(new BitmapDrawable());
            // 设置popupWindow以外为半透明0-1 0为全黑,1为全白
            backgroundAlpha(0.3f);
            // 添加pop窗口关闭事件
            this.setOnDismissListener(new poponDismissListener());
            // 设置动画--这里按需求设置成系统输入法动画
            this.setAnimationStyle(R.style.AnimBottom);
            // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
            CommodityAttributeView.setOnTouchListener(new View.OnTouchListener() {

                public boolean onTouch(View v, MotionEvent event) {

                    int height = CommodityAttributeView.findViewById(R.id.pop_layout)
                            .getTop();
                    int y = (int) event.getY();
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        if (y < height) {

                            dismiss();
                        }
                    }
                    return true;
                }
            });
        }
    }


    public void TagAdapNotify(mTagAdapter Adapter, int CcInt) {
        Adapter.getPreCheckedList().clear();
        if (CcInt != -1) {
            Adapter.setSelectedList(CcInt);
        }
        Adapter.notifyDataChanged();
    }


    /**
     * PopouWindow设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    /**
     * PopouWindow添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     *
     * @author cg
     */
    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }
    }

    /**
     * 尺寸的流式布局Adatper
     *
     * @author itzwh
     */
    class mTagAdapter extends TagAdapter<String> {

        private TextView tv;

        public mTagAdapter(Attribute ab) {
            super(ab);
        }

        @Override
        public View getView(FlowLayout parent, int position, Attribute t) {
            boolean is = false;
            //两个布局,一个是可点击的布局，一个是不可点击的布局
            List<String> st = t.FailureAliasName;
            if (st != null) {
                for (int i = 0; i < st.size(); i++) {
                    if (st.get(i).equals(t.aliasName.get(position))) {
                        is = true;
                    }
                }
            }
            if (!is) {
                tv = (TextView) mInflater.inflate(R.layout.popupwindow_tv, parent, false);
                tv.setText(t.aliasName.get(position));
            } else {
                tv = (TextView) mInflater.inflate(R.layout.popupwindow_tv1, parent, false);
                tv.setText(t.aliasName.get(position));
            }

            return tv;
        }
    }
}
